var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var cookieParser = require('cookie-parser');
var db = require('./models/db');
var setting = require('./setting');
var app = express();

// var mail = require('./commons/mail');
var UserModel = require('./models/User');
var auth = require('./commons/auth');

app.use(express.static('www'));
app.use( bodyParser.urlencoded({extended:false}) );
app.use(bodyParser.json());
app.use(cookieParser( setting.secret ));
app.use( session({
    secret: setting.secret ,
    resave:true,
    saveUninitialized:true,
    store: new MongoStore({
        // url: 'mongodb://localhost/sessionmongo'
        url:'mongodb://' + setting.host + '/' + setting.db
    })
}) )

app.use(auth.createSession);
app.use(function(req, res, next){
    res.locals.user = req.session.user;
    next();
})




app.get('/zc',function(req,res){
    UserModel.findOne({username:req.query.username}).exec(function(err,data){
      if (data) {
        return res.json({
          error: 1,
          msg: '用户已注册，请重新输入'
        })
      }
      var user = new UserModel(req.query);
      user.save(function (err) {
        if (!err) {
          res.json({
            error: 0,
            msg: '用户注册成功'
          })
        }
      })
    })
})


app.get('/login',function(req,res){
    // console.log(req.body);
  var username = req.query.username;
  var password = req.query.password;
  // 判断用户有没有注册
  UserModel.findOne({username:username}).exec(function(err, user){
    if( !user ){
      return res.json({
        error:'1',
        msg:'用户未注册，请注册'
      })
    }
    if( password == user.password && username == user.username ){
      // 设置用户登录的cookie数据
      res.cookie('username', user.username);

      return res.json({
        error:0,
        msg:'登录成功'
      })
    }
    res.json({
      error:1,
      msg:'密码错误，请重新输入'
    })
  })
})


// app.get('/exit',function(req,res){
//     res.clearCookie( setting.cookieName );
//     req.session.user = null;
//     res.json({
//         error:0,
//         msg:'退出成功'
//     })
// })
app.listen(3200,function(){
    console.log('服务器启动了');
})
